package com.lpy.spring;


import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @author: LiuPengYu
 * @date 2024/11/16 14:26
 */
public class LpyApplicationContext {
    private Class configClass;

    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    //单例池
    public static ConcurrentHashMap<String, Object> singletonObjectMap = new ConcurrentHashMap<>();

    private ArrayList<BeanPostProcessor> beanPostProcessors = new ArrayList<>();


    public LpyApplicationContext(Class configClass) throws ClassNotFoundException {
        this.configClass = configClass;
        //扫描BeanDefinition->存入beanDefinitionMap
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            //扫描路径 com.lpy.service ->包名 //需要扫描class 字节码文件
            String path = componentScanAnnotation.value();
            //相对路径
            path = path.replace(".", "/");
            //拿到类加载器
            ClassLoader classLoader = LpyApplicationContext.class.getClassLoader();
            //传入相对路径，获得绝对路径资源
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            System.out.println(file);
            if (file.isDirectory()) {
                //是文件夹拿到所有文件
                File[] files = file.listFiles();
                for (File f : files) {
                    //只关心class文件，筛选出来 先拿到文件绝对路径
                    String fileName = f.getAbsolutePath();
                    //关心是不是后缀是class结尾的
                    if (fileName.endsWith(".class")) {
                        //判断有没有component注解 用反射 要传类的全限定名
                        // 提取类的全限定名
                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class")).replace("\\", ".");
                        Class<?> claszz = classLoader.loadClass(className);
                        if (claszz.isAnnotationPresent(Component.class)) {
                            //这个类是不是对应接口的派生
                            if (BeanPostProcessor.class.isAssignableFrom(claszz)){
                                //是则生成对象
                                try {
                                    BeanPostProcessor instance = (BeanPostProcessor) claszz.newInstance();
                                    beanPostProcessors.add(instance);
                                } catch (InstantiationException e) {
                                    throw new RuntimeException(e);
                                } catch (IllegalAccessException e) {
                                    throw new RuntimeException(e);
                                }
                            }

                            Component component = claszz.getAnnotation(Component.class);
                            String beanName = component.value();
                            if ("".equals(beanName)) {
                                //短命传进去
                                beanName = Introspector.decapitalize(claszz.getSimpleName());
                            }
                            //生成一个 BeanDefinition 对象
                            BeanDefinition beanDefinition = new BeanDefinition();
                            //看有没有Scope注解 有则默认原型（多例）模式
                            if (claszz.isAnnotationPresent(Scope.class)) {
                                Scope scopeAnnotation = claszz.getAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            } else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinition.setType(claszz);
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    }
                }
            }
        }
        //看有没有单例bean，有则创建单例bean对象存入单例池 如果getBean的时候就从单例池里拿
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if ("singleton".equals(beanDefinition.getScope())) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjectMap.put(beanName, bean);
            }
        }
    }

    /**
     * 创建Bean 对象
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        //当前bean的类
        Class clazz = beanDefinition.getType();
        //反射访问构造方法 生成对象
        try {
            //实例化得到对象
            Object instance = clazz.getConstructor().newInstance();
            //对象属性赋值 模拟bean的生命周期
            //给加了Autowired的属性赋值 依赖注入模拟
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)) {
                    f.setAccessible(true);
                    f.set(instance, getBean(f.getName()));
                }
            }
            //Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                beanPostProcessor.postProcessBeforeInitialization(beanName,instance);
            }

            //初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }
            //初始化后的AOP BeanPostProcessor(bean的后置处理器)
            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName,instance);
            }

            return instance;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if ("singleton".equals(scope)) {
                Object singletonBean = singletonObjectMap.get(beanName);
                if (null == singletonBean) {
                    Object o = createBean(beanName, beanDefinition);
                    singletonObjectMap.put(beanName, o);
                }
                return singletonBean;
            } else {
                //多例创建bean对象
                return createBean(beanName, beanDefinition);
            }
        }
    }

}
